<template>
  <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :disabled="!canEdit"
      action="/"
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl"  :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script setup>
import { ref,watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import usePatternStore from "@/store/pattern";
const usePattern = usePatternStore()
const canEdit = ref(usePattern.modal==="edit")
watch(() => usePattern.modal, (newVal) => {
  if(newVal==="edit"){
    canEdit.value = true
  }else{
    canEdit.value = false
  }
})
const props = defineProps({
  icon: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(["subImg"])
const imageUrl = ref('')
watch(() => props.icon, (newVal) => {
  imageUrl.value = newVal
},{
  immediate: true
})

// 实现的功能是，上传一张图片，将图片转换为base64的格式，然后将base64的格式的字符串
const handleChange = (file) => {
  console.log(file.raw)
  file2Base64(file.raw).then(res => {
    imageUrl.value = res
    emits("subImg", res)
  })
}
const file2Base64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function () {
      resolve(reader.result)
    }
    reader.onerror = function (error) {
      reject(error)
    }
  })
}
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  color: #8c939d;
  width: 40px;
  height: 40px;
  overflow: hidden;
  text-align: center;
  object-fit: cover;
  object-position: center;
}

.avatar-uploader {
  width: 40px;
  height: 40px;
}

.avatar-uploader .el-upload {
  box-sizing: border-box;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  color: #8c939d;
  width: 40px;
  height: 40px;
  text-align: center;
}
</style>

